package com.qf.shiro;

import com.qf.pojo.DtsAdmin;
import com.qf.service.DtsAdminService;
import com.qf.service.DtsPermissionService;
import com.qf.service.DtsRoleService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Set;

public class AdminAuthorizingRealm extends AuthorizingRealm {
    //注入service对象
    @Autowired
    private DtsAdminService adminService;

    @Autowired
    private DtsRoleService roleService;

    @Autowired
    private DtsPermissionService permissionService;
    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //假装已经授权

//        DtsAdmin dtsAdmin = (DtsAdmin) principalCollection.getPrimaryPrincipal();
//        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();


        //1. 获取认证后的用户对象
        DtsAdmin admin = (DtsAdmin) getAvailablePrincipal(principalCollection);
        //2. 从用户对象中获取, 用户拥有的角色数组
        Integer[] roleIds = admin.getRoleIds();
        //3. 根据角色数组到数据库中查询到对应的用户名称集合
        Set<String> roles = roleService.queryByIds(roleIds);
        //4. 根据角色数组到数据库中查询到对应的权限字符串集合
        Set<String> permissions = permissionService.queryByRoleIds(roleIds);
        //5. 创建shiro框架的权限对象
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //6. 这个用户拥有的角色名称加入到shiro框架
        info.setRoles(roles);
        //7. 这个用户拥有的权限字符串集合加入到shiro框架
        info.setStringPermissions(permissions);
        //8. 返回权限对象
        return info;
    }


    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //1:用户名 密码
        String username = (String) token.getPrincipal();
        String password = new String((char[])token.getCredentials());

        DtsAdmin dtsAdmin = adminService.findAdmin(username);
        if(null == dtsAdmin){
            throw new UnknownAccountException();
        }
        //3:校验密码是否正确
        if(!dtsAdmin.getPassword().equals(password)){
            throw new IncorrectCredentialsException();//密码不正确
        }

        AuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(dtsAdmin,password,this.getName());
        return authenticationInfo;
    }

}
